<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        var obj = {
            users: [
                {
                    name: "xiaoli",
                    score: 60
                },
                {
                    name: "laowang",
                    score: 70
                },
                {
                    name: "xiaozhao",
                    score: 80
                },
                {
                    name: "xiaogao",
                    score: 90
                }
            ],
            //  sum:300
        }

        var newObj = Object.defineProperties(obj, {
            sum: {
                get: function () {
                    //  console.log(this.users);
                    // let result = 0;
                    // for (let i = 0; i < this.users.length; i++) {
                    //     result += this.users[i].score;
                    // }
                    // return result;

                    return this.users.reduce(function(pre,item){
                        return pre+item.score;
                    },0)
                }
            },
            avg:{
                get:function(){
                    // 总分数/总人数
                    // console.log(this.sum);
                    // console.log(this.users.length);
                    return Math.round(this.sum/this.users.length);
                }
            }
            
        });

    
        obj.users.push({
            name:"dawang",
            score:89
        });

        // console.log(newObj.sum);

        console.log(newObj.avg);
        




        //  console.log(obj.sum);

        //  function sum(arr){
        //     let result = 0;
        //     for(let i =0; i<arr.length;i++){
        //         result+=arr[i].score;
        //     }
        //     return result;
        //  }

        // let res = sum(obj.users);

        // console.log(res);

    </script>
</body>

</html>